package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.FriendModel;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.FriendsContract;
import com.jtech.together.util.BmobUtil;
import com.jtech.together.util.LetterUtil;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 我的好友
 * Created by wuxubaiyang on 2017/5/10.
 */
public class FriendsPresenter implements FriendsContract.Presenter {
    private Context context;
    private FriendsContract.View view;
    private UserModel myUser;

    public FriendsPresenter(Context context, FriendsContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
        //获取当前用户对象
        this.myUser = UserManager.getCurrentUser();
    }

    @Override
    public void loadFriendList() {
        new BmobQuery<FriendModel>()
                .addWhereEqualTo("user", myUser)
                .include("friendUser")
                .setLimit(1000)
                .findObjects(new FindListener<FriendModel>() {
                    @Override
                    public void done(List<FriendModel> list, BmobException e) {
                        if (null == e) {
                            //有好友则处理集合
                            if (list.size() > 0) {
                                handleFriendList(list);
                            } else {
                                //没有好友则直接返回
                                view.loadSuccess(list);
                            }
                        } else {
                            view.loadFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                        }
                    }
                });
    }

    /**
     * 处理好友列表
     *
     * @param friendModels
     */
    private void handleFriendList(List<FriendModel> friendModels) {
        Observable.just(friendModels)
                .subscribeOn(Schedulers.io())
                .map(new Function<List<FriendModel>, List<FriendModel>>() {
                    @Override
                    public List<FriendModel> apply(List<FriendModel> friendModels) throws Exception {
                        //遍历并处理所有对象获取首字母
                        for (int i = 0; i < friendModels.size(); i++) {
                            String nickName = friendModels.get(i).getFriendUser().getNickname();
                            String letter = "*";
                            if (!TextUtils.isEmpty(nickName)) {
                                letter = LetterUtil.getFirstLetter(nickName);
                            }

                            friendModels.get(i).setLetter(letter);
                        }
                        //字母排序
                        Collections.sort(friendModels, new LetterComparator());
                        //返回排序后的结果
                        return friendModels;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<FriendModel>>() {
                    @Override
                    public void accept(List<FriendModel> friendModels) throws Exception {
                        view.loadSuccess(friendModels);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        view.loadFail("好友排序失败，请重试");
                    }
                });
    }


    /**
     * 字母排序
     */
    private class LetterComparator implements Comparator<FriendModel> {
        @Override
        public int compare(FriendModel l, FriendModel r) {
            if (l == null || r == null) {
                return 0;
            }
            String lhsSortLetters = l.getLetter();
            String rhsSortLetters = r.getLetter();
            if (lhsSortLetters == null || rhsSortLetters == null) {
                return 0;
            }
            return lhsSortLetters.compareTo(rhsSortLetters);
        }
    }
}